package com.niit.white_box.service;

import com.niit.white_box.dto.LoginRequest;
import com.niit.white_box.dto.RegisterRequest;
import com.niit.white_box.entity.User;
import com.niit.white_box.mapper.UserMapper;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private final UserMapper userMapper;

    // logger 暂未使用

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    // 修改 UserService.java
    public User login(LoginRequest loginRequest) {
        String account = loginRequest.getAccount();
        String password = loginRequest.getPassword();
        if (account == null || password == null) {
            throw new IllegalArgumentException("账号和密码不能为空");
        }
        User user;
        if (account.contains("@")) {
            user = userMapper.findByEmailAndPassword(account, password);
        } else {
            user = userMapper.findByPhoneAndPassword(account, password);
        }
        return user;
    }

    public void register(RegisterRequest registerRequest) {
        // 校验参数
        if (registerRequest.getPhone() == null || registerRequest.getEmail() == null ||
                registerRequest.getPassword() == null || registerRequest.getConfirmPassword() == null) {
            throw new IllegalArgumentException("所有字段均不能为空");
        }
        if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
            throw new IllegalArgumentException("两次输入的密码不一致");
        }
        // 检查邮箱/手机号是否已注册
        if (userMapper.findByPhone(registerRequest.getPhone()) != null ||
                userMapper.findByEmail(registerRequest.getEmail()) != null) {
            throw new IllegalArgumentException("手机号或邮箱已注册");
        }
        // 自动生成nickname为"游客N"
        int maxNum = userMapper.getMaxGuestNumber();
        String nickname = "游客" + (maxNum + 1);

        User user = new User();
        user.setPhone(registerRequest.getPhone());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(registerRequest.getPassword());
        user.setUsername(registerRequest.getUsername());
        user.setNickname(nickname);
        user.setRoleId(2);

        userMapper.insertUser(user);
    }

    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    public void resetPasswordByPhone(String phone, String newPassword) {
        if (phone == null || newPassword == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (userMapper.findByPhone(phone) == null) {
            throw new IllegalArgumentException("手机号未注册");
        }
        int updated = userMapper.updatePasswordByPhone(phone, newPassword);
        if (updated == 0) {
            throw new IllegalStateException("重置失败，请重试");
        }
    }

    // 分页用户列表（支持多条件搜索）
    public java.util.Map<String, Object> pageUsers(int page, int size, String username, 
            String nickname, String phone, String status, String startDate, String endDate) {
        if (page <= 0) page = 1;
        if (size <= 0 || size > 200) size = 10;
        int offset = (page - 1) * size;
        java.util.List<User> records = userMapper.listUsers(offset, size, username, 
            nickname, phone, status, startDate, endDate);
        int total = userMapper.countUsers(username, nickname, phone, status, startDate, endDate);
        java.util.Map<String, Object> res = new java.util.HashMap<>();
        res.put("records", records);
        res.put("total", total);
        res.put("page", page);
        res.put("size", size);
        return res;
    }
    
    // 根据ID获取用户
    public User getUserById(int id) {
        return userMapper.findById(id);
    }
    
    // 更新用户
    public void updateUser(User user) {
        if (user.getId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        int updated = userMapper.updateUser(user);
        if (updated == 0) {
            throw new IllegalStateException("更新失败，用户不存在");
        }
    }
    
    // 删除用户
    public void deleteUser(int id) {
        if (id <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        int deleted = userMapper.deleteUser(id);
        if (deleted == 0) {
            throw new IllegalStateException("删除失败，用户不存在");
        }
    }
    
    // 搜索用户（带分页）
    public java.util.Map<String, Object> searchUsers(String keyword, int page, int size) {
        if (page <= 0) page = 1;
        if (size <= 0 || size > 200) size = 10;
        if (keyword == null) keyword = "";
        int offset = (page - 1) * size;
        java.util.List<User> records = userMapper.searchUsers(keyword, offset, size);
        int total = userMapper.countSearchUsers(keyword);
        java.util.Map<String, Object> res = new java.util.HashMap<>();
        res.put("records", records);
        res.put("total", total);
        res.put("page", page);
        res.put("size", size);
        return res;
    }
    
    // 新增用户（管理员添加）
    public void addUser(User user) {
        if (user.getPhone() == null || user.getEmail() == null) {
            throw new IllegalArgumentException("手机号和邮箱不能为空");
        }
        // 检查邮箱/手机号是否已注册
        if (userMapper.findByPhone(user.getPhone()) != null ||
                userMapper.findByEmail(user.getEmail()) != null) {
            throw new IllegalArgumentException("手机号或邮箱已注册");
        }
        // 设置默认值
        if (user.getRoleId() == null) {
            user.setRoleId(2);
        }
        if (user.getStatus() == null) {
            user.setStatus(0); // 0表示正常，1表示禁用
        }
        userMapper.insertUser(user);
    }
    
    // 根据ID修改密码
    public void updatePasswordById(int id, String newPassword) {
        if (id <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        if (newPassword == null || newPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        int updated = userMapper.updatePasswordById(id, newPassword);
        if (updated == 0) {
            throw new IllegalStateException("修改密码失败，用户不存在");
        }
    }
}

